﻿//  Copyright (c) 2011 Ray Liang (http://www.dotnetage.com)
//  Licensed MIT: http://www.opensource.org/licenses/mit-license.php

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Security;
using DNA.Mvc.Installation;
using DNA.Mvc.Security;
using System.Linq;

namespace DNA.Mvc.Controllers
{
    [InstallationGuard]
    public class InstallController : Controller
    {
        private IMembershipService MembershipService;

        public InstallController(IMembershipService membership)
        {
            this.MembershipService = membership;
        }

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Account()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        [HttpPost]
        public ActionResult Account(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                string[] reserves = new string[] { "host", "home", "index", "default", "{blog}", "sites", "{site}" };
                if (reserves.Contains(model.UserName.ToLower()))
                {
                    ModelState.AddModelError("", string.Format(Resources.language.Register_UserNameReserved, "\"" + model.UserName + "\""));
                }
                else
                {
                    MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email);

                    if (createStatus == MembershipCreateStatus.Success)
                    {
                        Roles.AddUserToRole(model.UserName, "administrators");
                        Roles.AddUserToRole(model.UserName, "guests");
                        return RedirectToAction("Account");
                    }
                    else
                    {
                        ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
                    }
                }
            }

            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        public ActionResult CreateWeb(string id)
        {
            ViewBag.Owner = id;
            return View();
        }

        [HttpPost]
        public ActionResult CreateWeb(Web web, string solution)
        {
            var logData = new List<TraceData>();

            try
            {
                var dbContext = DependencyResolver.Current.GetService<IDataContext>();
                web.Name = "home";
                var _vals = ObjectHelper.ConvertObjectToDictionary(web);
                var settings = new Dictionary<string, object>();
                foreach (var key in _vals.Keys)
                    settings.Add("Web." + key, _vals[key]);
                settings.Add("AppPath", Server.MapPath("~/"));

                var _service = new InstallationService();

                var package = dbContext.Solutions.Find(p => p.Name.Equals(solution, StringComparison.OrdinalIgnoreCase));
                var path = package.ResolvePhysicalPath("install.xml");

                dbContext.WidgetsSeed();

                _service.Install(path, HttpContext, settings);

                DnaConfig.SaveDomain(HttpContext);

                var data = _service.GetTraceResult();
                logData.AddRange(data);
            }
            catch (Exception e)
            {
                logData.Add(new TraceData("Installation fail! " + e.Message) { ErrorInfo = e, Category = "Error", IsWarn = true });
                return View("Log", logData);
            }

            if (logData.FirstOrDefault(t => t.IsError) != null)
                logData.Add(new TraceData("Installation fail some error occurs!") { Category = "Error", IsWarn = true });
            else
                logData.Add(new TraceData("Install successful!"));

            return View("Log", logData);
        }

        [HttpPost]
        public ActionResult Restart()
        {
            DnaConfig.Restart();
            return Redirect(Url.Action("Index", "Home"));
        }
    }
}